package com.mhs.sync;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import java.net.Socket;

import com.mhs.services.PublicVariable;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class ListenSignalSync extends Service{
	private static final String TAG = "ServiceListenSignalSync";
	boolean isRunning = false;
	Socket m_clientSock;
	private Thread thread;
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		Toast.makeText(this, "Service Listen Signal Sync Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");
		try {
			m_clientSock = new Socket(PublicVariable.getIpserver(), Integer.parseInt(PublicVariable.getPort()));
			//m_clientSock.setSoTimeout(15000);
			m_clientSock.setKeepAlive(true);
		} catch (Exception ex) {
			ex.printStackTrace();
			Toast.makeText(this, "Cannot connect to Server! Error:" + ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	
	@Override
	public void onDestroy() {
		Toast.makeText(this, "Service Listen Signal Sync Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");
		try {
			m_clientSock.close();
			isRunning = false;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
//	
//	Handler handler = new Handler() {
//		@Override
//		public void handleMessage(Message msg) {
//			String returnedValue = (String)msg.obj;
//			//do something with the value sent by the background thread here
//			//....
//			msgReturned.setText("returned by background thread: \n\n" 
//						       + returnedValue);
//			
//			bar1.incrementProgressBy(2);
//
//			//testing early termination
//			if (bar1.getProgress() == MAX_SEC){		
//				msgReturned.setText("Done \n back thread has been stopped");
//				isRunning = false;
//			}
//			
//			if (bar1.getProgress() == bar1.getMax()){
//				msgWorking.setText("Done");
//				bar1.setVisibility(View.INVISIBLE);	
//				bar2.setVisibility(View.INVISIBLE);
//			}
//			else {
//				msgWorking.setText("Working..." +
//						bar1.getProgress() );
//			}
//					
//		}
//	};
	
	@Override
	public void onStart(Intent intent, int startid) {
		Toast.makeText(this, "Service Listen Signal Sync Started", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onStart");
		thread = new Thread(new Runnable() {
			public void run() {
//				while (!Thread.interrupted()){
					try {
						try{
					        //PrintWriter out = null;
					        BufferedReader in = null;
					        try {
					            //out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(m_clientSock.getOutputStream())),true);
					            in = new BufferedReader(new InputStreamReader(m_clientSock.getInputStream(), "UTF8"));
					            //out.println(message);
					            String finalText = "";
					            String text = "";
								while ((text = in.readLine()) != null) {
						            finalText = text.replaceAll("[^a-z,A-Z,0-9]", "");
						            if(finalText.trim().compareTo("sync") == 0){
						            	break;
						            }else{
						            	// do nothing
						            	Thread.sleep(500);
						            }
						            break;
					            }
					            String txt = finalText;
					            if(txt.trim().compareTo("sync") == 0){
					            	// call service sync
					            	startService(new Intent(ListenSignalSync.this, com.mhs.sync.Sync.class));
//					            	Thread threadService = new Thread(new Runnable() {
//										public void run() {
//											startService(new Intent(ListenSignalSync.this, com.mhs.sync.Sync.class));
//										}
//									});
//					            	threadService.start();
					        		//stopService(new Intent(ListenSignalSync.this, com.mhs.sync.Sync.class));
					            }else{
					            	// do nothing
					            }
					        } catch(Exception e) { 
					            Log.e("TCP", "S: Error", e); 
					        } finally { 
					        	//m_clientSock.close();
					        } 
						}catch(Exception ex){
							ex.printStackTrace();
						}
//						for (int i = 0; i < MAX_SEC && isRunning; i++) {		
//							//try a Toast method here (will not work!)
//							//fake busy busy work here
//							Thread.sleep(1000);  //one second at a time
//							Random rnd = new Random();
//							
//							// this is a locally generated value
//							String data = "Thread Value: " + (int) rnd.nextInt(101);
//						
//							//we can see and change (global) class variables
//							data += "\n" + strTest + " " + intTest;
//							intTest++;
//							
//							//request a message token and put some data in it 
//							Message msg = handler.obtainMessage(1, (String)data);
//							
//							// if thread is still alive send the message					
//							if (isRunning) {
//								handler.sendMessage(msg);
//							}
//						}
					} catch (Throwable t) {
						// just end the background thread
						t.printStackTrace();
					}
//				}
			}
		});
		isRunning = true;
		thread.start();

	}
}
